<script setup>
import {ref, reactive, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";
import ElementPlus from "element-plus"; // 引入element-plus组件

// 表格引用
const tableRef = ref()

// 筛选表单
const filterForm = ref({
  name: '',
  storeId: ''
})

// 表格数据
const tableData = ref([])
const initData = () => {
  axios.get(`/dish/ingredient/${pageNum.value}/${pageSize.value}`).then((res) => {
    tableData.value = res.data.obj.data;
    total.value = res.data.obj.total;
  })
}
onMounted(()=>{
  initData();
  getStores();
  getCategories();
})

// 选中项
const selectedItems = ref([])

// 类别选项
const categories = ref([])
// 门店选项
const stores = ref([])
const getStores=()=>{
  axios.get('/dishManage/stores').then(res => {
    //将返回的数组对象转换为element需要的格式
    stores.value = res.data.map(item =>( {
      value : item.id,
      label : item.name
    }))
  });
}
//获取原料分类信息
const getCategories=()=>{
  axios.get('/dishManage/getAllIngredientCategoryName').then(res => {
    console.log(res.data)
    categories.value = res.data.map(item =>({
      value: item.id,
      label: item.name
    }))
  })
}


// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 50
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增原料')

const formData = ref({
  id: '',
  name: '',
  unit: '',
  stockQuantity: '',
  categoryId: '',
  storeId: ''
})

// 查询处理
const handleQuery = () => {
 axios.post(`/dishManage/searchIngredient/${pageNum.value}/${pageSize.value}`,filterForm.value ).then(res => {
   tableData.value=res.data.obj.data;
   total.value=res.data.obj.total;
 })
  // initData();
  // 这里应该调用API获取筛选后的数据
}
const handleSelectionChange = (val) => {
  selectedItems.value = [];
  selectedItems.value = val.map(item => item.id);
}

// 分页
const pageNum=ref(1)
const pageSize=ref(10)
let total=ref(1);
//分页组件
const { ComponentSize } = ElementPlus
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  if(filterForm.value.name!=null||filterForm.value.storeId!=null){
    handleQuery();
  }else {
    initData();
  }
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  pageNum.value=val;
  if(filterForm.value.name!=null||filterForm.value.storeId!=null){
    handleQuery();
  }else {
    initData();
  }

}
// 新增原料
const handleAdd = () => {
  dialogTitle.value = '新增原料'
  formData.value = {
    id: '',
    name: '',
    unit: '',
    stock: '',
    categoryId: null,
    storeId: ''
  }
  axios.get('/dishManage/stores').then(res => {
    //将返回的数组对象转换为element需要的格式
    stores.value = res.data.map(item =>({
      value: item.id,
      label: item.name
    }) );
  });

  axios.get('/dishManage/getAllIngredientCategoryName').then(res => {
    categories.value = res.data.obj.map(item =>({
      value: item.id,
      label: item.name
    }));
  });

  dialogVisible.value = true
}

// 编辑原料
const handleEdit = (row) => {
  dialogTitle.value = '编辑原料'
  // 根据 ID 获取原料信息
  axios.get(`/dishManage/getIngredientById/${row.id}`)
      .then(res => {
        // 检查后端返回的数据结构
        console.log('后端返回的数据:', res.data)

        if (res.data.code === 200) {
          // 如果 res.data.data 已经是 JavaScript 对象，直接使用
          formData.value = res.data.obj
          dialogVisible.value = true
        } else {
          ElMessage.error('获取原料信息失败')
        }
      })
      .catch(error => {
        console.error('获取原料信息失败:', error)
        ElMessage.error('获取原料信息失败')
      })
}
// 删除原料
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该原料吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/dishManage/ingredient/${row.id}`).then(res=>{
      initData();
      ElMessage.success('删除成功!!')
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}


const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 项吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    alert(selectedItems.value.length)
    // 删除逻辑
    // const selectedIds = selectedItems.value.map(item => item.id)
    // tableData.value = tableData.value.filter(item => !selectedIds.includes(item.id))
    axios.post(`/dishManage/ingredients`,selectedItems.value).then(res=>{
      initData();
      selectedItems.value = []
      ElMessage.success('批量删除成功')
    })

  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 确认提交
const handleConfirm = () => {
  if (!formData.value.name || !formData.value.unit || !formData.value.categoryId || !formData.value.storeId) {
    ElMessage.warning('请填写完整信息')
    return
  }
  if (formData.value.id) {
    // 编辑逻辑
    axios.post('/dishManage/editIngredient', formData.value).then(res => {
      if (res.data) {

        initData()
        dialogVisible.value = false
        ElMessage.success('修改成功')
      }
    })
  } else {
    // 新增逻辑
    axios.post('/dishManage/addIngredient', formData.value).then(res => {
      if (res.data) {
        initData()
        dialogVisible.value = false
        ElMessage.success('添加成功')
      }
    })
  }
}

// 全选/取消全选 (可通过调用 tableRef.value.toggleAllSelection() 实现)
</script>

<template>
  <div class="material-management">
    <!-- 筛选区域 + 操作按钮合并到一行 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="原料名称">
          <el-input v-model="filterForm.name" placeholder="请输入" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="所属门店">
          <el-select v-model="filterForm.storeId" placeholder="请选择门店" clearable style="width: 200px">
            <el-option v-for="store in stores"  :label="store.label" :value="store.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </el-form-item>

        <!-- 操作按钮移到查询按钮旁边 -->
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增原料</el-button>
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
          ref="tableRef"
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" align="center" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="unit" label="采购单位" width="120" align="center" />
        <el-table-column prop="stockQuantity" label="库存" width="120" align="center" />
        <el-table-column prop="categoryName" label="类别" width="120" align="center" />
        <el-table-column prop="storeName" label="所属门店" width="150" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 15, 20, 25]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible"
               :title="dialogTitle"
               width="600px">
      <el-form :model="formData"  label-width="100px">
        <el-form-item label="原料名称" prop="name" >
          <el-input v-model="formData.name" placeholder="请输入原料名称" />
        </el-form-item>
        <el-form-item label="采购单位" prop="unit" >
          <el-input v-model="formData.unit" placeholder="请输入采购单位" />
        </el-form-item>
        <el-form-item label="库存" prop="stockQuantity" >
          <el-input v-model="formData.stockQuantity"  placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="类别" prop="category" >
          <el-select v-model="formData.categoryId" placeholder="请选择类别" style="width: 100%">
            <el-option v-for="category in categories"  :label="category.label" :value="category.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属门店" prop="store" >
          <el-select v-model="formData.storeId" placeholder="请选择门店" style="width: 100%">
            <el-option v-for="store in stores" :key="store.value" :label="store.label" :value="store.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.material-management {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.table-section {
  flex: 1;
  margin-bottom: 20px;
}

/* 调整表格样式与菜品表一致 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  padding: 12px 0;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 按钮样式调整 */
.el-button {
  padding: 8px 15px;
}
</style>


